#include "entity.h"

using namespace GoldenAges;

CEntity::CEntity(void)
    : m_pSurface(nullptr),
      m_bIsVisible(true),
      m_iPosX(0),
      m_iPosY(0),
      m_iTilePosX(0),
      m_iTilePosY(0),
      m_iAlphaChannel(255)
{
}

CEntity::~CEntity(void)
{
    if(!m_pSurface)
        SDL_FreeSurface(m_pSurface);
}

bool CEntity::LoadData(TiXmlElement* pXMLData)
{
	return LoadImageFromFile(std::string(pXMLData->FirstChild("image")->FirstChild()->Value()));
}

TiXmlElement CEntity::SaveData(void)
{
    TiXmlElement ImageElm("image");
	TiXmlText ImageTxt(m_sImageFileName.c_str());
	ImageElm.InsertEndChild(ImageTxt);

	return ImageElm;
}

void CEntity::Think(const int &iElapsedTime)
{
}

void CEntity::Render(SDL_Surface *pDestSurf)
{
    if(!m_pSurface || !m_bIsVisible || !m_iAlphaChannel)
        return;

    SDL_Rect destrect;

    destrect.x = m_iPosX;
    destrect.y = m_iPosY;
    destrect.h = m_pSurface->h;
    destrect.w = m_pSurface->w;

    if(m_iAlphaChannel < 255)
        SDL_SetAlpha(m_pSurface, SDL_SRCALPHA, m_iAlphaChannel);

    SDL_BlitSurface(m_pSurface, &m_pSurface->clip_rect, pDestSurf, &destrect);
}

bool CEntity::LoadImageFromFile(const std::string& sFile)
{
	if(m_pSurface)
		SDL_FreeSurface(m_pSurface);

	SDL_Surface *pTempSurface;
	pTempSurface = SDL_LoadBMP(sFile.c_str());

	m_sImageFileName = sFile;

	if(!pTempSurface)
	{
		char czError[256];
		sprintf(czError, "Image '%s' could not be opened. Reason: %s", sFile.c_str(), SDL_GetError());
		fprintf(stdout, "ERROR: %s\n", czError);

		return false;
	}
	else
	{
		if(SDL_SetColorKey( pTempSurface, SDL_SRCCOLORKEY | SDL_RLEACCEL,
                     SDL_MapRGB(pTempSurface->format, 255, 0, 255)) == -1)
		{
			char czWarning[256];
			sprintf(czWarning, "Image '%s' can't be color keyed. Reason: %s", sFile.c_str(), SDL_GetError());
			fprintf(stdout, "WARNING: %s\n", czWarning);

            return false;
		}
	}

    m_pSurface = pTempSurface;

	return true;
}

SDL_Rect CEntity::GetEntityRect(void)
{
	SDL_Rect stTemp = {GetPosX(), GetPosY(), GetWidth(), GetHeight()};
	return stTemp;
}
